//
//  RadioDetailsTableViewController.m
//  PetTown
//
//  Created by lanou3g on 15/5/31.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "RadioDetailsTableViewController.h"
#import "RadioTitleView.h"
#import "RadioDetailsCell.h"
#import "JSONKit.h"
#import "UIImageView+WebCache.h"
#import "RadioPlayViewController.h"
#import "MBProgressHUD.h"
#import "UIScrollView+MJRefresh.h"
@interface RadioDetailsTableViewController ()
{
    MBProgressHUD * mbBar;
}
@end

@implementation RadioDetailsTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    //下拉刷新
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self readData];//读取数据
    [self setBarButtonItem];//设置BarButtonItem
    self.dataDiction = [NSMutableDictionary dictionary];
    self.radioUrlArray = [NSMutableArray array];
    self.titleArray = [NSMutableArray array];
    self.radioImgUrlArray = [NSMutableArray array];
    
}

//下拉刷新

- (void)headerRereshing{
    
    [self.tableView headerEndRefreshing];
}
//解析数据
- (void)readData{
    
    mbBar = [[MBProgressHUD alloc] initWithView:self.tableView];
    [self.tableView addSubview:mbBar];
    mbBar.labelText = @"正在加载..";
    [mbBar show:YES];
    
    NSURL * URL = [NSURL URLWithString:RadioDetailsAPI];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
    [request setHTTPMethod:@"POSY"];//设置请求方式
    NSString * dataStr = [NSString stringWithFormat:RadioDetailsSplicing,_radioid];
    NSData * data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    
    self.radioDetailsArray = [NSMutableArray array];
    //通过block方式请求
    NSOperationQueue * mainQueue = [NSOperationQueue mainQueue];
    __weak RadioDetailsTableViewController * radioPageTVC = self;
    [NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (nil == data) {
            return ;
        }
        NSMutableDictionary * dic = [data objectFromJSONData];
        NSMutableDictionary * diction = [dic objectForKey:@"data"];
        NSArray * array = [diction objectForKey:@"list"];
        radioPageTVC.dataDiction = [diction objectForKey:@"radioInfo"];
        for (NSMutableDictionary * dict in array) {
            RadioDetails * radioD = [[RadioDetails alloc] init];
            [radioD setValuesForKeysWithDictionary:dict];
            [radioPageTVC.radioDetailsArray addObject:radioD];
        }
        [self.tableView reloadData];
        [self setHeaderField];//设置表头
    }];

}

//设置BarButtonItem
-(void)setBarButtonItem{
    UIButton * retunButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    retunButton.frame = CGRectMake(0, 0, 32, 32);
    [retunButton setBackgroundImage:[UIImage imageNamed:@"ReturnPage.png"] forState:UIControlStateNormal];
    [retunButton addTarget:self action:@selector(leftBIClick) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem * leftBI = [[UIBarButtonItem alloc] initWithCustomView:retunButton];
    self.navigationItem.leftBarButtonItem = leftBI;
    self.navigationItem.title = _radioTitle;
}
//BI事件
- (void)leftBIClick{
    [self.navigationController popViewControllerAnimated:YES];
}
//设置表头
- (void)setHeaderField{
    self.radioTV = [[RadioTitleView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetWidth(self.view.frame)/3 * 2 + 20)];
    _radioTV.dataDiction = _dataDiction;
    self.tableView.tableHeaderView = _radioTV;
    self.navigationItem.title = _radioTV.title;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    //清除缓存
    SDImageCache * sdI = [SDImageCache sharedImageCache];
    [sdI clearDisk];
    [sdI clearMemory];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return _radioDetailsArray.count;
}

//设置cell显示内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RadioDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RadioDetailsCell" ];
    if (!cell) {
        cell = [[RadioDetailsCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"RadioDetailsCell"];
    }
    RadioDetails * radioD = _radioDetailsArray[indexPath.row];
    //给cell传值
    cell.radioDetails = radioD;
    //将播放页面需要得播放队列url添加进数组
    if ([radioD.musicUrl length] != 0) {
        [_radioUrlArray addObject:radioD.musicUrl];
        //将播放页面需要的title添加进数组
        [_titleArray addObject:radioD.title];
        //将播放页面需啊哟的图片添加进数组
        [_radioImgUrlArray addObject:radioD.coverimg];
    }
    //设置cell上图片显示
    NSURL * url = [NSURL URLWithString:[radioD coverimg]];
    [cell.leftImg sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"place.jpg"]];
    
    [MBProgressHUD hideHUDForView:self.tableView animated:YES];

    
    return cell;
}

//设置点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RadioPlayViewController * radioPlayVC = [[RadioPlayViewController alloc] init];
  
    //将播放队列及标题和图片传到下一页面
    radioPlayVC.radioUrlArray = _radioUrlArray;
    radioPlayVC.titleArray = _titleArray;
    radioPlayVC.radioImgUrlArray = _radioImgUrlArray;
    radioPlayVC.index = indexPath.row;
    [self.navigationController pushViewController:radioPlayVC animated:YES];
}
//设置cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
